import React, { useState, useEffect } from 'react'
import '../../../System/Account_management/component/Css/Account_management.css'
import { Input, Button, DatePicker, Modal, Form, Select, } from 'antd';

import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Flex, message, Upload } from 'antd';
import type { GetProp, UploadProps } from 'antd';

// 调用定义接口
import {addads,getads } from '../../../../request/api'
const { RangePicker } = DatePicker;

export default function User_title(props) {
    const { getTitle, getuserlist } = props;

    let [item, setitem] = useState('')//搜索框
    let [num, setnum] = useState(0)//当前检索到多少条数据
    const [modal2Open, setModal2Open] = useState(false); //控制模态框是否显示


    let [name, setname] = useState([])//名称
    let [location, setlocation] = useState([])//位置
    let [sort,setsort] = useState([])//排序
    let [state, setstate] = useState([])//状态
    let [type,settype] = useState([])//类型
    let [image,setimage] = useState('')//图片

    // 搜索
    const search = async () => {
        let res = await getads({ item: item })
        setnum(res.data.length)
        getTitle(res.data)
        setitem('')
    }

    // 添加账号
    const add = async () => {
        console.log(111);
        
        let from = {
            name: name,
            img:image,
            location: location,
            sort: sort,
            state: state,
            count:0,
            add_Time: new Date().toLocaleString(),
            type:type,
        }
        let res = await addads({ from: from })
        if (res.code == 200) {
            getuserlist(200)
            alert('添加成功')
            setModal2Open(false)
            setname('')
            setimage('')
            setsort('')
            setstate('')
            setlocation('')
            settype('')
            setImageUrl('')
        }
    }



    const [componentSize, setComponentSize] = useState<SizeType | 'default'>('default');
    const onFormLayoutChange = ({ size }: { size: SizeType }) => {
        setComponentSize(size);
    };





    // 图片
    type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

    const getBase64 = (img: FileType, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };

    const beforeUpload = (file: FileType) => {
        // return isJpgOrPng && isLt2M;
    };
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    const handleChange: UploadProps['onChange'] = (info) => {        
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as FileType, (url) => {
                setLoading(false);
                setImageUrl(url);
                setimage(info.file.response.img)
            });
        }
    };

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );



    return (
        <div>
            <div className='xitong_Title'>
                <div className='xitong_Title_left'>
                    <Input size="large" placeholder="请输入内容" prefix='热词名称：' style={{ marginBottom: '20px' }} value={item} onChange={(event) => {
                        setitem(event.target.value)
                    }} />
                    <Button size="large" style={{ marginRight: '10PX' }} onClick={() => {
                        search()
                    }}>检索</Button>
                    <Button size="large" style={{ marginRight: '10PX' }} onClick={() => {
                        search()
                    }}>重置</Button>
                    <Button size="large" style={{ display: name == '操作日志' ? 'none' : 'inline-block' }} onClick={() => {
                        setModal2Open(true)
                    }}>新建广告</Button>
                </div>
                <div className='xitong_Title_time'>
                    <RangePicker showTime style={{ height: '40px', display: name == '操作日志' ? '' : 'none' }}></RangePicker>
                </div>
                <span className='xitong_user'>当前共检索到{num}条内容</span>
                <Modal
                    title='新建广告'
                    centered
                    open={modal2Open}
                    onOk={() => add()}
                    onCancel={() => setModal2Open(false)}
                >
                    <Form
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        layout="horizontal"
                        initialValues={{ size: componentSize }}
                        onValuesChange={onFormLayoutChange}
                        size={componentSize as SizeType}
                        style={{ maxWidth: 600 }}
                    >
                        <Form.Item label="广告名称">
                            <Input value={name} onChange={(e) => {
                                setname(e.target.value)
                            }} />
                        </Form.Item>
                        <Form.Item label="广告位置">
                            <Select value={location} onChange={(e) => {
                                setlocation(e)
                            }}>
                                <Select.Option value='首页轮播图'>首页轮播图</Select.Option>
                                <Select.Option value='首页推荐位置'>首页推荐位置</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item label="排序">
                            <Input value={sort} onChange={(e) => {
                                setsort(e.target.value)
                            }} />
                        </Form.Item>
                        <Form.Item label="状态" >
                            <Select value={state} onChange={(e) => {
                                setstate(e)
                            }}>
                                <Select.Option value='true'>上线</Select.Option>
                                <Select.Option value='false'>下线</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item label="广告图片">
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="http://localhost:3000/content/index/imgupload"
                                beforeUpload={beforeUpload}
                                onChange={handleChange}
                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item label="跳转类型" >
                            <Select value={type} onChange={(e) => {
                                settype(e)
                            }}>
                                <Select.Option value='站内'>站内</Select.Option>
                                <Select.Option value='外链'>外链</Select.Option>
                            </Select>
                        </Form.Item>
                    </Form>

                </Modal>
            </div>
        </div>
    )
}

